package com.example.camerademo.countdownview;

import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.example.camerademo.R;

import java.util.ArrayList;
import java.util.List;

import cn.iwgang.countdownview.CountdownView;

/**
 * @author ypk
 * 创建日期：2021/12/3  15:01
 * 描述：
 */
public class MyAdapter extends BaseQuickAdapter<ItemInfo, BaseViewHolder> {


    public MyAdapter(List<ItemInfo> mDataList) {
        super(R.layout.item, mDataList);
    }

    //CountdownView mCvCountdownView;

    @Override
    protected void convert(@NonNull BaseViewHolder viewHolder, ItemInfo item) {
        viewHolder.setText(R.id.tv_desc, item.getTitle());
        CountdownView mCvCountdownView = viewHolder.getView(R.id.cv_countdownView);

        long leftTime = item.getEndTime() - System.currentTimeMillis();
        refreshTime(mCvCountdownView, leftTime);

        mCvCountdownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                int layoutPosition = viewHolder.getLayoutPosition();
                Toast.makeText(getContext(), layoutPosition + " 倒计时结束", Toast.LENGTH_SHORT).show();
                System.out.println(layoutPosition + " 倒计时结束");
            }
        });
    }

    private void refreshTime(CountdownView mCvCountdownView, long leftTime) {
        if (leftTime > 0) {
            mCvCountdownView.start(leftTime);
        } else {
            mCvCountdownView.stop();
            mCvCountdownView.allShowZero();
        }
    }

    @Override
    public void onViewAttachedToWindow(@NonNull BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        int pos = holder.getAbsoluteAdapterPosition();
        Log.d("MyViewHolder", String.format("mCvCountdownView %s is attachedToWindow", pos));

        ItemInfo itemInfo = getData().get(pos);

        CountdownView mCvCountdownView = holder.getView(R.id.cv_countdownView);
        long leftTime = itemInfo.getEndTime() - System.currentTimeMillis();
        refreshTime(mCvCountdownView, leftTime);

    }

    @Override
    public void onViewDetachedFromWindow(@NonNull BaseViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        CountdownView mCvCountdownView = holder.getView(R.id.cv_countdownView);
        mCvCountdownView.stop();
    }
}
